'use client';

import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

// 配置 NProgress
NProgress.configure({ 
  showSpinner: false,
  minimum: 0.3,
  easing: 'ease',
  speed: 500,
  trickleSpeed: 200
});

let timer: NodeJS.Timeout | null = null;
let isAnimating = false;

export function RouteChangeProgress() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    // 如果已经在动画中，先重置
    if (isAnimating) {
      if (timer) clearTimeout(timer);
      NProgress.done();
      NProgress.remove();
    }

    // 开始新的进度条
    isAnimating = true;
    document.body.style.background = '#001529';  // 设置背景色
    NProgress.start();
    
    timer = setTimeout(() => {
      NProgress.done();
      isAnimating = false;
      timer = null;
      // 添加过渡效果
      document.body.style.transition = 'background 0.3s ease';
      document.body.style.background = '';  // 恢复原始背景色
    }, 500);  // 与 NProgress 的速度保持一致

    return () => {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      document.body.style.background = '';
      document.body.style.transition = '';
      NProgress.done();
      isAnimating = false;
    };
  }, [pathname, searchParams]);

  return null;
} 